import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

 let car=window.JSON.parse(localStorage.getItem('cart')|| '[]')

const store=new Vuex.Store({
  state:{
      
      cart:car
  },
  mutations:{
      addToCar(state,goods){
          let flag=true;
         state.cart.some(item=>{
             if(item.id==goods.id){
                 item.count+=goods.count;
                 flag=false;
                 return true
             }
         })
         if(flag){
             state.cart.push(goods);
         }
          localStorage.setItem('cart',window.JSON.stringify(state.cart))

      },
      updateGoodsCount(state,goods){
          state.cart.some(item=>{
              if(item.id==goods.id){
                  item.count=goods.count
                  return true
              }
          })

          localStorage.setItem('cart',window.JSON.stringify(state.cart))

      },
      delFromCart(state,id){
        state.cart.some((item,i)=>{
            if(item.id==id){
                state.cart.splice(i,1)
                return true
            }
        })
        localStorage.setItem('cart',window.JSON.stringify(state.cart))
      },
      changeSelectS(state,obj){
         state.cart.some(item=>{
             if(item.id==obj.id){
                 item.selected=obj.selected
                 //console.log(item.id+"---"+obj.selected)
                 return true
             }
         })
         localStorage.setItem('cart',window.JSON.stringify(state.cart))
      }
  },
  getters:{
      totalcount(state){
          let c=0;
          let cc=0;
          state.cart.forEach(item=> c+=item.count)
        //   setTimeout(()=>{
    
        //   })
          return c
      },
      idstr(state){
          let arr=[];
        state.cart.forEach(item=>arr.push(item.id))
        return arr.join(',');
      },
      countObj(state){
          let o={}
          state.cart.forEach(item=> o[item.id]=item.count)
          return o;
      },
      seletedObj(state){
        let o={}
        state.cart.forEach(item=> o[item.id]=item.selected)
        return o;
    },
    selectescount(state){
        let c=0;
        state.cart.forEach(item=>{
            if(item.selected){
                c+=item.count;
            }
        })
        return c
    },
    amount(state){
       let c=0;
       state.cart.forEach(item=>{
           if(item.selected){
               c+=item.count*item.price
           }
       })
       return c
    }
  }
})

export default store;